import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AxiosService } from "../../../axios.service"
import { DatePipe } from "@angular/common";
import * as XLSX from 'xlsx';
import * as FileSaver from 'file-saver';
@Component({
  selector: 'app-listfault',
  templateUrl: './listfault.component.html',
  styleUrls: ['./listfault.component.scss'],
  providers: [DatePipe],

})
export class ListfaultComponent implements OnInit {
  datatime;//时间
  jgx;//多少个结果
  line4;//哪条线
  name4;//哪个设备
  sn4;//sn
  kaishitime;//开始时间
  endtime;//结束时间
  listdata;//所有表格内容
  downloadz = [];//下载
  constructor(
    public activatedRoute: ActivatedRoute,
    public axios: AxiosService,
    private datePipe: DatePipe,

  ) { }

  ngOnInit(): void {
    // 获取上个页面传来的数据
    this.activatedRoute.params.subscribe((data) => {
      this.line4 = data["line"]
      this.name4 = data["name"]
      this.sn4 = data["sn"]
    })
    this.kaishitime = "";
    this.endtime = "";
    this.getdata();
  }
  // 修改搜索时间
  Search() {
    this.kaishitime = this.datePipe.transform(this.datatime[0], "yyyy-MM-dd HH") + ":00";
    this.endtime = this.datePipe.transform(this.datatime[1], "yyyy-MM-dd HH") + ":00";
    //console.log(this.kaishitime, this.endtime);
    this.getdata();
  }
  // 获取后台数据
  getdata() {
    this.axios.axiosPost("QueryFAMachineYRDownload", {
      "starttime": this.kaishitime, "endtime": this.endtime, "machineSN"
        : this.sn4
    }).then((data) => {
      //console.log(data);
      this.listdata = data["order"]
      this.jgx = data["order"].length;
    })
  }
  download() {
    let list = [];
    this.listdata.forEach(item => {
      list.push({
        序號: item.xvhao,
        機種: item.jizhong,
        缐別: item.xianbie,
        站點: item.zhandian,
        名稱: item.name,
        設備類型: item.type,
        設備財編: item.caibian,
        編號: item.bianhao,
        "i4.0 IP": item.ip,
        異常信息: item.yichang,
        開始時間: item.start,
        結束時間: item.end,
        持續時長: item.time,
      });
    });

    const fileName = this.line4 + this.name4 + "故障詳情"
    const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(list);

    worksheet['!cols'] = [
      { wch: 5 },
      { wch: 5 },
      { wch: 5 },
      { wch: 5 },
      { wch: 14 },
      { wch: 15 },
      { wch: 22 },
      { wch: 7 },
      { wch: 16 },
      { wch: 12 },
      { wch: 10 },
      { wch: 10 },
      { wch: 10 },
    ];
    const workbook: XLSX.WorkBook = { Sheets: { "data": worksheet }, SheetNames: ['data'] };
    const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
    const data: Blob = new Blob([excelBuffer], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'
    });
    FileSaver.saveAs(data, fileName + '.xlsx');
  }

}
